import XLSXS from 'xlsx-style-fixed-ty'
const font = { name: "宋体", sz: 34 }
const font_bottom = { name: "宋体", sz: 28 }

function alignment (horizontal = 'center', vertical = 'center') {
	return {
		horizontal,
		vertical,
	}
}

/**
 * 导出
 * @param {*} array 
 * @param {*} param1 
 */
export function downloadExl(array, { countPrice, fileName = '货单' }) {
	let tmpdata = array[0];
	const { result, SheetNames } = pageResult(array);
	console.log(result, SheetNames);
	let keyMap = []; //获取keys
	for (var k in tmpdata) {
		keyMap.push(k);
	}

	// 1.初始化pageTmpdata
	var pageTmpdata = result.map(i => ({}));
	// 2.添加表头和表尾
	pageTmpdata.forEach((item, index) => {
		item['A1'] = {
			v: '交城国斌食品批发',
			s: {
				alignment: alignment(),
				font: { // 单元格中字体的样式与颜色设置
					sz: 65,
					name: "宋体",
					bold: true
				},
			}
		}
		item['A2'] = {
			v: '购货单位：',
			s: {
				alignment: alignment('left'),
				font,
			}
		}
		item['C2'] = {
			v: getNowFormatDate(),
			s: {
				alignment: alignment('right'),
			}
		}
		item['A19'] = {
			v: '合计：',
			s: {
				alignment: alignment('left'),
				border: {
					top: { style: "thin" },
					left: { style: "thin" },
					bottom: { style: "thin" },
					right: { style: "thin" },
				},
			}
		}
		//合计总价填充到最后一页
		if (index == pageTmpdata.length - 1) {
			// console.log('test:' + countPrice);
			item['B19'] = {
				v: '共' + '   ' + countPrice + '     ' +  '元 ',
				s: {
					font: { // 单元格中字体的样式与颜色设置
						sz: 54,
						name: "宋体",
					},
					alignment: alignment('right'),
					border: {
						top: { style: "thin" },
						bottom: { style: "thin" },
					},
				}
				
			}
		} else {
			item['B19'] = {
				v: '',
				s: {
					border: {
						top: { style: "thin" },
						bottom: { style: "thin" },
					},
				}
			}
		}

		item['C19'] = item['D19'] = item['E19'] = item['F19'] = item['G19'] = {
			v: '',
			s: {
				border: {
					top: { style: "thin" },
					bottom: { style: "thin" },
				},
			}
		}
		item['H19'] = {
			v: '',
			s: {
				border: {
					top: { style: "thin" },
					left: { style: "thin" },
					bottom: { style: "thin" },
					right: { style: "thin" },
				},
			}
		}
		item['A20'] = {
			v: '代理:统一饮料(阿萨姆)/统一方便面(小当家/汤达人)',
			// v: '地址: 交城县西汾阳村驴肉馆北50米',
			s: {
				font: font_bottom,
				alignment: alignment('left'),
			}
		}
		item['E20'] = {
			v: '地址:交城县西汾阳村驴肉馆北50米',
			s: {
				font: font_bottom,
				alignment: alignment('left'),
			}
		}
		item['A21'] = {
			v: '手机号/微信:13834361709 18636430746',
			s: {
				font: font_bottom,
				alignment: alignment('left'),
			}
		}
		item['E21'] = {
			v: '有退货一月内退换不影响二次销售',
			s: {
				font: font_bottom,
				alignment: alignment('left'),
			}
		}
		//<====合并单元格 将excel看作一个以（0，0）坐标系，s为start代表开始合并位置，e为end代表结束合并位置
		item["!merges"] = [
			{
				s: { c: 0, r: 0 },
				e: { c: 7, r: 0 }
			},
			{
				s: { c: 0, r: 1 },
				e: { c: 1, r: 1 }
			},
			{
				s: { c: 2, r: 1 },
				e: { c: 7, r: 1 }
			},
			{
				s: { c: 1, r: 18 },
				e: { c: 7, r: 18 }
			},
			{
				s: { c: 0, r: 19 },
				e: { c: 3, r: 19 }
			},
			{
				s: { c: 4, r: 19 },
				e: { c: 7, r: 19 }
			},
			{
				s: { c: 0, r: 20 },
				e: { c: 3, r: 20 }
			},
			{
				s: { c: 4, r: 20 },
				e: { c: 7, r: 20 }
			},
		];
	})
	// 3.添加表格
	result.forEach((item, index) => {
		item.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
				v: v[k],
				// String.fromCharCode(65)代表A
				position: String.fromCharCode(65 + j) + (i + 1 + 2)
			}))).reduce((prev, next) => prev.concat(next))
			.forEach((v, i) => {
				pageTmpdata[index][v.position] = {
					v: v.v,
					s: {
						border: {
							top: { style: "thin" },
							left: { style: "thin" },
							bottom: { style: "thin" },
							right: { style: "thin" },
						},
					}
				}
			});
	})
	console.log(keyMap, tmpdata, pageTmpdata);
	// 4.设置表格的行宽度，以及打印设置等
	pageTmpdata.forEach((item) => {
		//默认值[0.7, 0.7, 0.75, 0.75, 0.3, 0.3]
		item['!margins'] = { left:0.3, right: 0.3, top: 0.5, bottom: 0.75 } //打印时页面边距
		item['!pageSetup'] = {
			paperSize: '11', // 打印纸张类型A5
		  scale: '30', // 打印缩放比例
		  orientation: 'portrait',	// 打印方向
		}
		if (!item['!cols']) item['!cols'] = [] //列宽
		//if (!item['!rows']) item['!rows'] = [{ hpt: 500 }, { hpx: 500 }]  //行高
		// 设置行高，如果写{}代表自适应，如果写{ hpx: 30 }代表行高30榜
		item['!rows'] = Array(21).fill(null).map((i, index) => {
			if([0].includes(index))	return { hpx: 140 }
			if([18].includes(index))	return { hpx: 70 }
			if([1, 19, 20].includes(index))	return { hpx: 55 }
			if(index >= 2 && index <= 17)	return { hpx: 80 }
		})
		// 设置列宽
		item['!cols'] = [
			{ wpx: 80 },
			{ wpx: 100 },
			{ wpx: 100 },
			{ wpx: 570 },
			{ wpx: 195 },
			{ wpx: 100 },
			{ wpx: 140 },
			{ wpx: 140 },
		]
		
		const outputPos = Object.keys(item); // ['A1', 'A2']
		outputPos.forEach(i => {
			if(item[i].s){
				//如果说对齐方式不存在，那就设置默认垂直居中
				if(!item[i].s.alignment){
					item[i].s.alignment =  {
						vertical: "center",
					}
				}
				//如果说对齐方式不存在，那就设置默认垂直居中
				if(!item[i].s.font){
					item[i].s.font = font
				}
			}
			if (i[0] === 'A' && !['A2', 'A19', 'A20', 'A21', 'A22', 'A23'].includes(i)) {
				item[i].s.alignment.horizontal = "center"
			}
			if (i[0] === 'D') {
				item[i].s.alignment.wrapText = true // 超出换行
			}
			if (['G', 'H', 'I'].includes(i[0])) {
				//item[i].t = 'n' // t：单元格的类型 'n'数字、'e'错误、's'字符串、'd'日期 
			}
		})
	})
	// 5.填充tmpWB，然后下载
	var tmpWB = {
		SheetNames, // ['第1页', ],
		Sheets: {}
	};
	pageTmpdata.forEach((i, n) => {
		const itemSheetName = SheetNames[n]; // sheet页名称
		const itemSheet = Object.assign({},
			i, //内容
			{
				'!ref': 'A1' + ':' + 'I23' //设置填充区域
				// '!ref': outputPos[0] + ':' + outputPos[xx] //设置填充区域
			}
		)
		tmpWB.Sheets[itemSheetName] = itemSheet;
	})
	console.log(tmpWB.Sheets);

	//关键一步： XLSX.write()开始编写Excel表格, changeData()将数据处理成需要的输出的格式
	const StrData = changeData(XLSXS.write(tmpWB, {
		bookType: 'xlsx',
		bookSST: false,
		type: 'binary'
	}))
	const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器
	console.log('开始下载');
	dell()
	const fname = `/${fileName} ${getDayTimer()}.xlsx`
	fs.writeFile({
		filePath: wx.env.USER_DATA_PATH + fname,
		// filePath: wx.env.USER_DATA_PATH + `/${getNowFormatDate()}.xlsx`, // wx.env.USER_DATA_PATH 指定临时文件存入的路径，后面字符串自定义
		data: StrData,
		encoding: 'binary', //二进制流文件必须是 binary
		success(res) {
			console.log('成功');
			wx.openDocument({
				// 打开文档
				filePath: wx.env.USER_DATA_PATH + fname,
				// filePath: wx.env.USER_DATA_PATH + `/${getNowFormatDate()}.xlsx`, //拿上面存入的文件路径
				showMenu: true, // 显示右上角菜单
				success: function(res) {

				},
				fail: function() {
					console.log('失败');
				},
			})
		},
		fail: function() {
			console.log('失败');
		},
	})
}

// 返回分页数据
function pageResult(array) {
	let result = [],
		title = {};
	for (var k in array[0]) {
		title[k] = k;
	}
	for (let i = 0; i < array.length; i += 15) {
		let arr = array.slice(i, i + 15);
		if (arr.length < 15) {
			for (let i = arr.length; i < 15; i++) {
				arr.push({
					"序号": i + 1,
					"点货": "",
					"已配": "",
					"货品": "",
					//"条形码": "",
					"规格": "",
					"数量": "",
					"单价": "",
					"总价": ""
				})
			}
		}
		result.push(arr);
	}
	console.log(result);
	result.forEach(i => i.unshift(title)); // 插入表头
	// result.forEach(i => i.push({})); // 插入表wei
	result.forEach(i => {
		i.forEach((item, index) => {
			if (index !== 0) {
				item["序号"] = index;
			}
		})
	})
	const SheetNames = result.map((item, index) => `第${index + 1}页`);
	return {
		result,
		SheetNames
	};
}

function changeData(s) {
	//如果存在ArrayBuffer对象(es6)最好采用该对象
	if (typeof ArrayBuffer !== 'undefined') {
		//1.创建一个字节长度为s.length的内存区域
		let buf = new ArrayBuffer(s.length)
		//2.创建一个指向buf的Unit8视图，开始于字节0,直到缓冲区的末尾
		let view = new Uint8Array(buf)
		//3.返回指定位置的字符的Unicode编码
		for (let i = 0; i != s.length; ++i) {
			view[i] = s.charCodeAt(i) & 0xff
		}
		return buf
	} else {
		let buf = new Array(s.length)
		for (let i = 0; i != s.length; ++i) {
			buf[i] = s.charCodeAt(i) & 0xff
		}
		return buf
	}
}

function getDayTimer() {
	var date = new Date()
	// var y = date.getFullYear()
	var m = date.getMonth() + 1
	m = m < 10 ? ('0' + m) : m
	var d = date.getDate()
	d = d < 10 ? ('0' + d) : d
	var currentdate = '2023' + m + d;
	var hh = date.getHours()
	hh = hh < 10 ? ('0' + hh) : hh
	var mm = date.getMinutes()
	mm = mm < 10 ? ('0' + mm) : mm
	var ss = date.getSeconds()
	ss = ss < 10 ? ('0' + ss) : ss
	var time = hh + '' + mm + '' + ss;
	return currentdate + "" + time
}
//删除缓存文件
function dell() {
	const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器
	fs.readdir({
		dirPath: wx.env.USER_DATA_PATH,
		success(res) {
			//    console.log("文件列表",res)
			let indexVal = res.files.length;
			res.files.forEach((el) => {
				let name = (wx.env.USER_DATA_PATH + el).replace(/usr/g, "usr/");
				fs.unlink({
					filePath: name,
					fail(e) {
						//   console.log('文件删除失败：', e)

					},
					success(succ) {
						indexVal++;
						if (indexVal == 0) {

						}
						console.log('文件删除成功：', succ);
					}
				})
			})
		}
	})
}

//获取当前日期函数
function getNowFormatDate() {
	let date = new Date(),
		year = date.getFullYear(), //获取完整的年份(4位)
		month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
		strDate = date.getDate() // 获取当前日(1-31)
	if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
	if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
	return `${year}-${month}-${strDate}`
}